<?php

    namespace yaliSDK\utils;
    use yaliSDK\utils\IdWork;
    class IdentifierHelper {
        public static function generateNo($type = 1) {
//            list($usec, $sec) = explode(" ", microtime());
//            $usec = substr(str_replace('0.', '', $usec), 0, 4);
//            $str = IdentifierHelper::generate_random(2, 1);
            $ip = $_SERVER['SERVER_ADDR'];
            $array = explode('.', $ip);
            $sum = 0;
            foreach ($array as $i) {
                $sum += $i;
            }
            $idword = new IdWork($sum,rand(1,31));
            $str = $idword->nextId();
            $usec = rand(1,9999);
            if ($type == 1) {
                return 'O' .$str.$usec;
            } elseif ($type == 2) {
                return 'C' . $str.$usec;
            }
        }

        public static function generate_id_random() {
            $d = request()->time();
            $usec = substr($d, count($d)-4, 3);
            return $usec . IdentifierHelper::generate_random(6, 1,rand(1,999999));
        }

        public static function generate_order_id_random() {
            $d = request()->time();
            $usec = substr($d, count($d)-4, 3);
            return $usec . IdentifierHelper::generate_random(7, 1).rand(1,999);
        }
        public static function generate_random($len = 6, $type = '', $addChars = '') {
            switch ($type) {
                case 0:
                    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
                    break;
                case 1:
                    $chars = str_repeat('0123456789', 3).$addChars;
                    break;
                case 2:
                    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
                    break;
                case 3:
                    $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
                    break;
                default :
                    // 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
                    $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
                    break;
            }
            if ($len > 10) {//位数过长重复字符串一定次数
                $chars = $type == 1 ? str_repeat($chars, $len) : str_repeat($chars, 5);
            }
            $chars = str_shuffle($chars);
            $str = substr($chars, 0, $len);
            return $str;
        }
    }